import React, { useEffect, useMemo, useRef, useState } from 'react'
import { Link, useHistory } from 'react-router-dom'
import { useDispatch } from 'react-redux'
import classNames from 'classnames'
import { Header, AlertTip } from 'src/components'
import { checkExsis, sendLogin, getcaptchas, accountLogin } from 'src/api/getData'
import * as actionType from 'src/redux/action-type'
import './index.scss'
// 登录
const Login = () => {
    const history = useHistory();
    const dispatch = useDispatch();

    const [loginWay, setLoginWay] = useState(false)
    const [showPassword, setShowPassword] = useState(false)
    const [phoneNumber, setPhoneNumber] = useState()
    const [mobileCode, setMobileCode] = useState()
    const [validate_token, setValidateToken] = useState()
    const [computedTime, setComputedTime] = useState(0)
    // const [userInfo, setUserInfo] = useState()
    const [userAccount, setUserAccount] = useState()
    const [passWord, setPassWord] = useState()
    const [captchaCodeImg, setCaptchaCodeImg] = useState()
    const [codeNumber, setCodeNumber] = useState()
    const [showAlert, setShowAlert] = useState(false)
    const [alertText, setAlertText] = useState()

    const timerRef = useRef(null);

    useEffect(() => {
        getCaptchaCode();
    }, [])


    //改变登录方式
    const changeLoginWay = () => {
        setLoginWay(!loginWay)
    }

    //是否显示密码
    const changePassWordType = () => {
        setShowPassword(!showPassword)
    }

    //获取验证吗，线上环境使用固定的图片，生产环境使用真实的验证码
    const getCaptchaCode = async () => {
        let res = await getcaptchas();
        setCaptchaCodeImg(res.code)
    }

    //判断手机号码
    const rightPhoneNumber = useMemo(() => {
        return /^1\d{10}$/gi.test(phoneNumber)
    }, [phoneNumber])

    //获取短信验证码
    const getVerifyCode = async () => {
        if (rightPhoneNumber) {
            setComputedTime(30);
            timerRef.current = setInterval(() => {
                setComputedTime(computedTime - 1)
                if (computedTime === 0) {
                    clearInterval(timerRef.current)
                }
            }, 1000)

            //判读用户是否存在
            let exsis = await checkExsis(phoneNumber, 'mobile');
            if (exsis.message) {
                setShowAlert(true);
                setAlertText(exsis.message)
                return
            } else if (!exsis.is_exists) {
                setShowAlert(true);
                setAlertText('您输入的手机号尚未绑定')
                return
            }
            //发送短信验证码
            let res = await mobileCode(phoneNumber);
            if (res.message) {
                setShowAlert(true);
                setAlertText(res.message)
                return
            }
            setValidateToken(res.validate_token)
        }
    }

    //发送登录信息
    const mobileLogin = async () => {
        let res;
        if (loginWay) {
            if (!rightPhoneNumber) {
                setShowAlert(true);
                setAlertText("手机号码不正确")
                return
            } else if (!(/^\d{6}$/gi.test(mobileCode))) {
                setShowAlert(true);
                setAlertText("短信验证码不正确")
                return
            }
            //手机号登录
            res = await sendLogin(mobileCode, phoneNumber, validate_token);
        } else {
            if (!userAccount) {
                setShowAlert(true);
                setAlertText("请输入手机号/邮箱/用户名")
                return
            } else if (!passWord) {
                setShowAlert(true);
                setAlertText("请输入密码")
                return
            } else if (!codeNumber) {
                setShowAlert(true);
                setAlertText("请输入验证码")
                return
            }
            //用户名登录
            res = await accountLogin(userAccount, passWord, codeNumber);
        }
        // setUserInfo(res)
        //如果返回的值不正确，则弹出提示框，返回的值正确则返回上一页
        if (!res.user_id) {
            setShowAlert(true);
            setAlertText(res.message)
            if (!loginWay) getCaptchaCode();
        } else {
            //记录用户信息
            dispatch({
                type: actionType.RECORD_USERINFO,
                info: res
            })
            history.go(-1);
        }
    }

    // 关闭Alert
    const onClose = () => {
        setShowAlert(false);
    }

    return <div className="page_login">
        <Header
            title={loginWay ? '登录' : '密码登录'}
            goBack
            changeLogin={<div className="change_login" onClick={changeLoginWay}>{loginWay ? "密码登录" : "短信登录"}</div>}
        ></Header>
        {
            loginWay ? <form className="loginForm">
                <section className="input_container phone_number">
                    <input type="text"
                        placeholder="账号密码随便输入"
                        name="phone"
                        maxLength="11"
                        value={phoneNumber}
                        onInput={(e) => setPhoneNumber(e.target.value)}
                    />
                    {!computedTime && <button onClick={getVerifyCode}
                        className={classNames({ right_phone_number: rightPhoneNumber })}
                    >获取验证码</button>}
                    {!!computedTime && <button>已发送({computedTime}s)</button>}
                </section>
                <section className="input_container">
                    <input type="text" placeholder="验证码" name="mobileCode" maxLength="6"
                        value={mobileCode}
                        onInput={e => setMobileCode(e.target.value)}
                    />
                </section>
            </form> : <form className="loginForm">
                <section className="input_container">
                    <input type="text" placeholder="账号"
                        value={userAccount}
                        onInput={(e) => setUserAccount(e.target.value)}
                    />
                </section>
                <section className="input_container">

                    <input type={!showPassword ? "password" : "text"} placeholder="密码"
                        value={passWord}
                        onInput={(e) => { setPassWord(e.target.value) }}
                    />

                    <div className={classNames('button_switch', { change_to_text: showPassword })}>
                        <div className={classNames('circle_button', { trans_to_right: showPassword })}
                            onClick={changePassWordType}></div>
                        <span>abc</span>
                        <span>...</span>
                    </div>
                </section>
                <section className="input_container captcha_code_container">
                    <input type="text" placeholder="验证码" maxLength="4" value={codeNumber} onInput={e => setCodeNumber(e.target.value)} />
                    <div className="img_change_img">
                        {
                            captchaCodeImg && <img src={captchaCodeImg} alt="" />
                        }
                        <div className="change_img" onClick={getCaptchaCode}>
                            <p>看不清</p>
                            <p>换一张</p>
                        </div>
                    </div>
                </section>
            </form>
        }
        <p className="login_tips">
            温馨提示：未注册过的账号，登录时将自动注册
        </p>
        <p className="login_tips">
            注册过的用户可凭账号密码登录
        </p>
        <div className="login_container" onClick={mobileLogin}>登录</div>
        {
            !loginWay && <Link to="/forget" className="to_forget">重置密码？</Link>
        }
        {
            showAlert && <AlertTip showHide={showAlert} onClose={onClose} alertText={alertText}></AlertTip>
        }
    </div>
}

export default Login